﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_PN
{
    public partial class BaoCaoSo13_Update : MyFromBase
    {
        private static int sID = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToControls();
            }
        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("BaoCaoMau13");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {

                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                tdTenDonVi.InnerText = "(" + dtDV.Rows[0]["MaDV"] + ") " + dtDV.Rows[0]["TenDV"];

                sql = "Select ID,TenDM From tblDanhMuc Where MaDM='" + MyConst.DanhMuc.KyBaoCao.Ma + "' ";
                SqlDataReader reKyBaoCao = SqlHelper.ExecuteReader(CommandType.Text, sql);
                clsDataBind.CreateCombo("Tất cả", reKyBaoCao, cboKyBaoCao, 1, 0);
            }
        }

        /// <summary>
        /// Bind Data vào gridview
        /// </summary>
        private void BindDataToGrid()
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCao", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));

            string sql = "SELECT BC.*,CB.TenCanBo,dv.TenDV,ChucVu FROM dbo.tblBaoCaoMau13 BC " +
                         "INNER JOIN dbo.tblCanBo CB ON CB.ID = BC.CanBoID " +
                         "INNER JOIN dbo.tblDonVi DV ON DV.ID = CB.DonViID " +
                         "WHERE KyBaoCaoID_DM = @KyBaoCao AND BC.DonViID = @DonViID AND IsCommon <>1";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            if (dt.Rows.Count == 0)
            {
                btnLuuBaoCao.CommandName = MyConst.Action.Addnew;
            }
            else
            {
                BindDataToTextField();
                btnLuuBaoCao.CommandName = MyConst.Action.Update;
            }
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        #region Events

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void BindDataToTextField()
        {
            string sql = "SELECT * FROM dbo.tblBaoCaoMau13 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND IsCommon = 1";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count != 0)
            {
                txtSoBaoCao.Text = dt.Rows[0]["CM_SoBaoCao"].ToString();
                txtNgayBaoCao.Text = dt.Rows[0]["CM_ThoiGianBaoCao"].ToString();
            }
        }

        protected void cboKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKyBaoCao.SelectedIndex > 0)
            {
                btnLuuBaoCao.Visible = true;
                grvData.Visible = true;
                btnThemTT.Visible = true;
                grvData.EditIndex = -1;
                BindDataToGrid();
            }
            else
            {
                btnLuuBaoCao.Visible = false;
                grvData.Visible = false;
                btnThemTT.Visible = false;
            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            int UserID = Convert.ToInt32(Session["userid"]);
            if (btnLuu.CommandName == MyConst.Action.Addnew)
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
                arrParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
                arrParams.Add(SqlHelper.CreateParameterObject("@CanBoID", SqlDbType.Int, ParameterDirection.Input, txtCanBoID.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
                string sql = "INSERT INTO dbo.tblBaoCaoMau13( KyBaoCaoID_DM ,DonViID ,CanBoID ,IsCommon ,CreateDate ,UpdateDate ,UserID) " +
                             "VALUES  ( @KyBaoCaoID_DM,@DonViID,@CanBoID,0,GETDATE(),GETDATE(),@UserID)";
                int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                if (result > 0)
                {
                    BindDataToGrid();
                    MyCommon.AddMessage(this.Page.Master, "Thêm cán bộ thành công", MyConst.MessageType.Success);
                    formUpdate.Visible = false;
                }
                else
                {

                    MyCommon.AddMessage(this.Page.Master, "Quá trình thêm mới lỗi", MyConst.MessageType.Error);
                }
            }
            else if (btnLuu.CommandName == MyConst.Action.Update)
            {
                string sql = "UPDATE dbo.tblBaoCaoMau13 SET CanBoID = @CanBoID, UpdateDate=GETDATE(),UserID = @UserID WHERE ID = @ID";
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@CanBoID", SqlDbType.Int, ParameterDirection.Input, txtCanBoID.Text));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, sID));
                int result = SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                if (result > 0)
                {
                    BindDataToGrid();
                    MyCommon.AddMessage(this.Page.Master, "Cập nhật cán bộ thành công", MyConst.MessageType.Success);
                    formUpdate.Visible = false;
                }
                else
                {
                    MyCommon.AddMessage(this.Page.Master, "Cập nhật cán bộ lỗi", MyConst.MessageType.Success);
                }
            }
        }

        protected void LoadDataToControl(int ID)
        {
            string sql = "SELECT BC.ID,CB.ID AS CanBoID,CB.TenCanBo,CB.ChucVu,DV.TenDV FROM dbo.tblBaoCaoMau13 BC INNER JOIN dbo.tblDonVi DV " +
                         "ON DV.ID = BC.DonViID INNER JOIN dbo.tblCanBo CB ON CB.ID = BC.CanBoID WHERE BC.ID = @ID";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            lblCanBo.Text = dt.Rows[0]["TenCanBo"].ToString();
            txtCanBoID.Text = dt.Rows[0]["CanBoID"].ToString();
            lblChucVu.InnerHtml= dt.Rows[0]["ChucVu"].ToString();
            lblDonVi.InnerHtml = dt.Rows[0]["TenDV"].ToString();
        }
        #endregion Events


        #region GridCommand

        protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(sender, e);
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            sID = Convert.ToInt32(e.CommandArgument);
            string sCommandName = e.CommandName;


            if ((sCommandName == AIC_PN.MyConst.Action.Update))
            {
                formUpdate.Visible = true;
                LoadDataToControl(sID);
                btnLuu.CommandName = AIC_PN.MyConst.Action.Update;
            }
            else if ((sCommandName == AIC_PN.MyConst.Action.Delete))
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM dbo.tblBaoCaoMau13 WHERE ID = " + sID);
                MyCommon.AddMessage(this.Page.Master, "Xóa cán bộ thành công", MyConst.MessageType.Success);
                BindDataToGrid();
            }
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvData.EditIndex = e.NewEditIndex;
            BindDataToGrid();
        }



        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvData.PageIndex = e.NewPageIndex;
            BindDataToGrid();
        }


        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            BindDataToGrid();
        }

        #endregion GridCommand

        protected void btnLuuBaoCao_Click(object sender, EventArgs e)
        {
            String sql = "SELECT * FROM dbo.tblBaoCaoMau13 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND IsCommon = 1";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));

            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count == 0)
            {
                btnLuuBaoCao.CommandName = MyConst.Action.Addnew;
            }
            else
            {
                btnLuuBaoCao.CommandName = MyConst.Action.Update;
            }

            if (btnLuuBaoCao.CommandName == MyConst.Action.Addnew)
            {
                string sSQL = "INSERT INTO dbo.tblBaoCaoMau13( KyBaoCaoID_DM ,DonViID ,CM_SoBaoCao ,CM_ThoiGianBaoCao ,IsCommon ,CreateDate ,UpdateDate ,UserID)" +
                              "VALUES ( @KyBaoCaoID_DM,@DonViID,@CM_SoBaoCao,@CM_ThoiGianBaoCao,1,GETDATE(),GETDATE(),@UserID)";

                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
                lstParameter.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_SoBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtSoBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThoiGianBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtNgayBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(Session["userid"])));

                SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);
                MyCommon.AddMessage(this.Master, "Lưu thông tin báo cáo thành công", MyConst.MessageType.Success);
            }
            else
            {
                string sSQL = "UPDATE dbo.tblBaoCaoMau13 SET CM_SoBaoCao = @CM_SoBaoCao, CM_ThoiGianBaoCao = @CM_ThoiGianBaoCao " +
                                "Where IsCommon=1 And DonViID=" + MyCommon.GetDonViID(Session["userid"].ToString()) + " And KyBaoCaoID_DM=" + cboKyBaoCao.SelectedValue;

                List<SqlParameter> lstParameter = new List<SqlParameter>();
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_SoBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtSoBaoCao.Text.Trim()));
                lstParameter.Add(SqlHelper.CreateParameterObject("@CM_ThoiGianBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtNgayBaoCao.Text.Trim()));


                SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);

                MyCommon.AddMessage(this.Master, "Lưu thông tin báo cáo thành công", MyConst.MessageType.Success);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = false;
        }

        protected void btnThemTT_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            lblChucVu.InnerHtml = "chức vụ";
            txtCanBoID.Text = "";
            lblCanBo.Text = "Chọn cán bộ";
            lblDonVi.InnerHtml = "đơn vị";
            btnLuu.CommandName = MyConst.Action.Addnew;
        }
    }
}
